package com.baikeyang.app.controller.api.ActivityTools.v1;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baikeyang.common.bean.ResponseResult;
import com.baikeyang.common.bean.wx.AuthCode2Session;
import com.baikeyang.common.model.WxUser;
import com.baikeyang.service.WxUser.IWxUserService;
import com.baikeyang.service.user.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;

/**
 * @Author     : BaiKeyang
 * @Date       : Created in 2020/5/20 14:51
 * @Description:
 * @Modified By: 
 * @Version: $
 */
@RestController("activityToolsWXAuth")
@RequestMapping(value = "app/v1/activityTools/auth/wx")
public class WXAuthentication {

    @Autowired
    private IWxUserService wxUserService;
    //@Autowired
    //private IUserService userService;

    static final String URL = "https://api.weixin.qq.com/sns/jscode2session";
    static final String APP_ID = "wx4a1d601a16931946";  // 小程序ID
    static final String APP_SECRET = "771e781707bda321a2667920f1a4f222";  // 小程序密钥

    /**
     * 根据Code获取进行微信登陆，并获取当前用户的唯一标识ID
     * @param code
     * @doc https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
     * @return
     */
    @RequestMapping(value = "goLogin")
    public AuthCode2Session goLogin(String code) {
        String _ur = URL + "?appid=" + APP_ID + "&secret=" + APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        String res = HttpUtil.get(_ur);
        AuthCode2Session authCode = JSON.parseObject(res, AuthCode2Session.class);
        if(null == authCode.getErrcode() && StrUtil.isEmpty(authCode.getErrmsg())){
            WxUser wxUser = new WxUser();
            wxUser.setLoginName(authCode.getOpenid());
            Long flag = wxUserService.saveWxUser(wxUser);
            if(flag > 0){
                authCode.setUserId(flag);
            }
        }
        return authCode;
    }





    @RequestMapping(value = "updateUserInfo", method = {RequestMethod.POST})
    public ResponseResult updateUser(WxUser wxUser) {
        return wxUserService.updateWxUserById(wxUser);
    }




}
